import yaml
from configs.setting import FILE_PATH
import os


def read_yaml(yaml_path):
    """
    读取yaml文件数据
    :param yaml_path: 文件路径
    :return:
    """
    try:
        with open(yaml_path, 'r', encoding='utf-8') as file:
            data = yaml.safe_load(file)
            return data
    except UnicodeDecodeError:
        print(f"{yaml_path}文件编码格式错误，--尝试使用utf-8去解码yaml文件发生错误，请确保你的yaml文件是utf-8格式！")
    except yaml.YAMLError as e:
        print(f"Error:读取yaml文件失败，请检查格式 -{yaml_path},{e}")
    except Exception as e:
        print(f"读取{yaml_path}文件时出现异常，原因：{e}")


def write_yaml(value):
    """
    yaml文件写入
    :param value: 写入的文件必须为字典类型
    :return:
    """
    file_path = FILE_PATH["extract"]
    if not os.path.exists(file_path):
        with open(file_path, "w"):
            pass
    file = None
    try:
        file = open(file_path, "a", encoding="utf-8")
        if isinstance(value, dict):
            write_data = yaml.dump(value, allow_unicode=True, sort_keys=False)
            file.write(write_data)
        else:
            print("写入的数据必须为字典类型！")
    except Exception as e:
        print(f"写入的yaml文件出现异常，原因{e}")
    finally:
        file.close()


def clear_yaml():
    """
    清空extract.yaml文件
    :return:
    """
    with open(FILE_PATH["extract"], "w") as f:
        f.truncate()


def get_extract_yaml(node_name, sub_node_name=None):
    """
    用于获取extract.yaml文件的数据
    :param node_name: 第一级k值
    :param sub_node: 下级k值
    :return:
    """
    file_path = FILE_PATH["extract"]
    try:
        with open(file_path, "r", encoding="utf-8") as file:
            extract_data = yaml.safe_load(file)
        if sub_node_name is None:
            return extract_data[node_name]
        else:
            return extract_data.get(node_name, {}).get(sub_node_name)
    except yaml.YAMLError as e:
        print(f"Error:读取yaml文件失败，请检查格式 -{file_path},{e}")
    except Exception as e:
        print(f"Error:未知异常 - {e}")


if __name__ == '__main__':
    res = get_extract_yaml("goodsId", 0)
    print(res)
